#-*-coding:utf-8-*-
'''
This module will achieve the LZW algorithm.
'''
from fileoperate import FileOperate
class LZW:
    '''
    Achieve the LZW algorithm
    '''
    def __init__(self,bits = 12):
        '''
        the bits used for record the units
        '''
        self.bits = bits  #refer to the size of the dict.
        self.cdict = ''
        self.posid = 256
        self.initially()

    def initially(self):
        '''
        Get the initial values.
        '''
        self.cdict = dict()
        for i in range(256):
            self.cdict[chr(i)] = self.GetBitsPos(i)

    def GetBitsPos(self,i):
        '''
        get the bits pos
        '''
        k = bin(i)[2:]
        if len(k) < self.bits:
            k = '0'*(self.bits - len(k)) + k
        return [int(j) for j in k]

    def AddaKey(self,key):
        '''
        Add an item in the dictionary.
        '''
        #c = self.GetBitsPos(self.posid)
        self.cdict[key] = self.GetBitsPos(self.posid)
        self.posid += 1

    def Encoding(self,instr):
        '''
        instr is the str which need to be code.
        '''
        w = ''  # w is the prefix
        outlist = list()
        for k in enumerate(instr,0):
            i = w + k[1]
            if self.cdict.has_key(i):
                w = i
            else:
                #print w
                outlist.extend(self.cdict[w])
                self.AddaKey(i)
                w = k[1]
        else:
            #print w
            outlist.extend(self.cdict[w])

        fo = FileOperate()
        j = len(outlist)
        if j % 8 != 0:
            outlist.extend([0 for i in range(8 - (j % 8))])         #if the bits is not enough ,program will fill zero.
        return fo.BitsToBytes(outlist)

    def Decoding(self,instr):
        '''
        Decode the string
        '''
        fo = FileOperate()
        klist = fo.BytesToBits(instr)
        klent = len(klist)
        for i in range(0,klent,self.bits):



    def test(self):
        '''
        test.
        '''
        a = 'ababcbababaaaaaaa'
        print len(a)
        o = self.Encoding(a)
        print len(o)
        print o

if __name__ == '__main__':
    c = LZW()
    c.test()


